package com.magicsoft.app.helper;

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.boyuan.huijiaoyu.R;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.magicsoft.app.wcf.AsyncHttpServiceHelper;
import com.magicsoft.app.wcf.listener.GetTwoRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.CustomAlertDialog;

public class UpdateVersionHelper {
	private Context context;

	public Boolean isShowing = false;

	public UpdateVersionHelper(Context context) {
		this.context = context;
	}

	/**
	 * 检查是否有新版本
	 * 
	 * @param context
	 */
	public void checkUpdate(final PostRecordResponseListener listener) {

		String localVersionCode = SharePreferenceHelper.getStringValue(context,
				SharePreferenceHelper.SERVERVERSIONNUM);

		// String requestUrl = Constant.GETVERSION
		// + "?platform=android&versionCode=" + localVersionCode;

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.GETVERSION + getParamString
				+ "&platform=android&versionCode=" + localVersionCode;

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);

				try {

					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONObject contentObject = response
								.getJSONObject("content");

						String versionName = contentObject
								.getString("versionName");
						String desc = contentObject.getString("desc");
						String android = contentObject.getString("android");
						boolean upgrade = contentObject.getBoolean("upgrade");

						if (upgrade) {
							// SharePreferenceHelper.setStringValue(context,
							// SharePreferenceHelper.SERVERVERSIONNUM,
							// remoteVer + "");

							SharePreferenceHelper.setStringValue(context,
									SharePreferenceHelper.CLIENTURLPATH,
									android);

							String title = context.getResources().getString(
									R.string.new_version)
									+ versionName;
							String content = desc;

							if (listener != null) {
								listener.onFinish(context.getResources()
										.getString(R.string.vision_findnew));
							}

							showUpgrade(title, content);
						} else {
							if (listener != null) {
								listener.onFailed(context
										.getResources()
										.getString(R.string.present_new_version));
							}
						}
					}


				} catch (Exception e) {

					if (listener != null) {
						listener.onFailed(context.getResources().getString(
								R.string.present_new_version));
					}
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);

				if (listener != null) {
					listener.onFailed(responseString);
				}
			}

		});

	}

	/**
	 * 弹出升级框
	 * 
	 * @param context
	 * @param title
	 * @param content
	 */
	public void showUpgrade(String title, String content) {

		isShowing = true;

		final CustomAlertDialog dialog = new CustomAlertDialog(context,
				R.style.qr_dialog);
		dialog.setCancelable(false);
		dialog.show();
		// 标题
		TextView tv_title = (TextView) dialog.findViewById(R.id.dialog_title);
		tv_title.setText(title);
		// 内容
		TextView tv_content = (TextView) dialog
				.findViewById(R.id.dialog_content);
		tv_content.setText(content);
		// 确定按钮
		Button btn_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				dialog.cancel();

				Log.e("upgrade dialog", "jump to service");

				new ApkHelper(context).showDownloadDialog();
				// Intent updateIntent = new Intent(context,
				// UpdateVersionService.class);
				//
				// context.startService(updateIntent);

				isShowing = false;

			}
		});

	}

	/**
	 * 获取用户应用权限
	 */
	public void getStatus(final GetTwoRecordListener<String, String> listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.STATUS + getParamString;

		Log.i("getStatus111111", requestUrl);

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);
				try {
					Log.i("getStatus", response.toString());

					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONObject contentObject = response
								.getJSONObject("content");

						String avaliable = contentObject.getString("avaliable");
						String msg = contentObject.getString("message");
						if (listener != null) {
							listener.onFinish(avaliable, msg);
						}
					} else {
						if (listener != null)
							listener.onFailed(message);
					}

				} catch (Exception e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(responseString);

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(throwable.toString());
			}
		});

	}

}
